package cn.jhz.learn.community_dynamic.common.util;

import com.google.common.primitives.Bytes;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.stream.Stream;

import static java.util.stream.Collectors.joining;


/**
 * 讲明文的字符串加密层密文字符串的工具类
 * @author Administrator
 *
 */

public class EncodeUtil {
	static private final String KEY = "machine_005@jhz.cn";
	
	private EncodeUtil() {}

	public static byte[] md5(byte[] key) throws NoSuchAlgorithmException {

		MessageDigest md = MessageDigest.getInstance("MD5");//这个参数就是加密的算法

		md.update(key);

		return md.digest(KEY.getBytes());
	}

	public static byte[] base64(byte[] key){
		return Base64.getEncoder().encode(key);
	}

	//SHA-1加密算法
	public static String sha1(String...key) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			Stream.of(key).map(String::getBytes).forEach(md::update);

			return Bytes.asList(md.digest(KEY.getBytes()))
					.stream()
					.map(b->String.format("%02x", b))//%02x,一个byte类型整数----> 2位十六进制字符来表示
					.collect(joining());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String sha1(byte[] key) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(key);

			return Bytes.asList(md.digest(KEY.getBytes()))
					.stream()
					.map(b->String.format("%02x", b))//%02x,一个byte类型整数----> 2位十六进制字符来表示
					.collect(joining());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	//SHA-256加密算法
	public static String sha512(byte[] key) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-512");
			md.update(key);

			return Bytes.asList(md.digest(KEY.getBytes()))
					.stream()
					.map(b->String.format("%02x", b))//%02x,一个byte类型整数----> 2位十六进制字符来表示
					.collect(joining());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null; 
	}
	
	static public String signatureCode(byte[] value) throws NoSuchAlgorithmException {
		byte[] first = md5(value);
		byte[] second = base64(value);
		byte[] result = Arrays.copyOf(first, first.length + second.length);
		System.arraycopy(second, 0, result, first.length, second.length);
		return sha512(result);
	}

	
	public static void main(String[] args) throws NoSuchAlgorithmException {
		
		System.out.println(signatureCode("abc".getBytes()));
	}
}
